package com.ys.util;

import com.ys.pojo.Administrators;
import com.ys.pojo.Publsa;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.logging.Logger;

/**
 * aop的增强处理
 */
@Aspect
@Component
public class AddAdvice {
    private Logger logger = Logger.getLogger("com.ys");

    @Around("execution(* com.ys.service.Impl.*.adds*(..))")
    public Object arround(ProceedingJoinPoint jp){
        //声明对象为null
        Object obj = null;
        //声明对象数组，从jp中取出所有对象
        try {
            logger.info("前置增强");
            Object[] objs = jp.getArgs();
            if(objs[0] instanceof Publsa){
                Publsa publics = (Publsa)objs[0];
                publics.setAtime(LocalDateTime.now());
                Session session = SecurityUtils.getSubject().getSession();
                Administrators administrators = (Administrators)session.getAttribute("objs");
                if(administrators!=null){
                    publics.setAname(administrators.getId());
//                    System.out.println(administrators.getId()+"当前的id");
                }
            }
            obj = jp.proceed();
            logger.info("后置增强");
        }catch (Throwable throwable) {
            logger.info("异常处理");
            throwable.printStackTrace();
        } finally {
            logger.info("最终增强");
        }
        return obj;
    }


    @Around("execution(* com.ys.service.Impl.*.upds*(..))")
    public Object arrounds(ProceedingJoinPoint jp){
        //声明对象为null
        Object obj = null;
        //声明对象数组，从jp中取出所有对象
        try {
            logger.info("前置增强");
            Object[] objs = jp.getArgs();
            if(objs[0] instanceof Publsa){
                Publsa publics = (Publsa)objs[0];
                publics.setBtime(LocalDateTime.now());
                Session session = SecurityUtils.getSubject().getSession();
                Administrators administrators = (Administrators)session.getAttribute("objs");
                if(session!=null){
                    publics.setBname(administrators.getId());
                    System.out.println(administrators.getId()+"当前的id");
                }
            }
            obj = jp.proceed();
            logger.info("后置增强");
        }catch (Throwable throwable) {
            logger.info("异常处理");
            throwable.printStackTrace();
        } finally {
            logger.info("最终增强");
        }
        return obj;
    }
}
